import {
  adressDetailServer,
  adressNewAddServer,
  adressNewEditServer,
  adressDeleteServer,
  allAddressesServer,
  couponListServer,
  hotCouponListServer,
  directionalCouponListServer,
  receiveDirectionalCouponServer,
  couponProductsInfoServer,
  createCouponServer,
  getCouponProductInCartPriceServer,
  myCouponServer,
  myGiftCardListServer,
  orderCouponListServer,
  couponShopListServer,
  myGiftCardServer,
  giftCardListServer,
  myGiftCardAmountServer,
  myGiftCardTransactionListServer,
  bindGiftCardServer,
  giftCardInfoServer,
  rechargeAmountServer,
  giftCardStoreListServer,
  payGiftCardServer,
  orderListServer,
  activityListServer,
  activityProductAmtServer,
  activityProductListServer,
  getDistrictServer,
  getInvoiceConfigServer,
  selectProductCouponListServer,
  activityReducesServer,
  moduleActivityListServer,
  productListServer,
  getAppConfigurationServer,
} from '@/services/giftCard';
import Taro from '@tarojs/taro';
import { sleep } from '@/utils/helper';
import { getUsableSelectedCouponList, resetSelectedStatus } from '@/dataTransfer/coupon.js';
import { dealPayloadParams } from './commonFunc';
import { getDefaultOptions } from '../dataTransfer/product';

export default {
  namespace: 'giftCard',
  state: {
    // 活动中的商品列表（新）SPU
    productList: [],
    productListParams: {},
    productListPagination: {},
    productListFinished: false,

    // 自定义页面获取活动分页列表
    moduleActivityList: [],
    moduleActivityListParams: {},
    moduleActivityListPagination: {},
    moduleActivityListFinished: false,

    // 获取满减活动的阶梯信息
    activityReduces: undefined,

    // 未登录时, 领取优惠券数据存储, 用于登录后直接领取优惠券
    pendingCoupon: undefined,

    // 活动中的商品分页列表
    activityProductList: [],
    activityProductListParams: {},
    activityProductListPagination: {},
    activityProductListFinished: false,

    // 活动适用商品金额结算
    activityProductAmt: {},

    // 活动分页列表
    activityList: [],
    activityListParams: {},
    activityListPagination: {},
    activityListFinished: false,

    // 获取礼品卡储值记录
    orderList: [],
    orderListParams: {},
    orderListPagination: {},
    orderListFinished: false,

    // 获取礼品卡店铺列表
    giftCardStoreList: [],
    giftCardStoreParams: {},
    giftCardStorePagination: {},
    giftCardStoreFinished: false,

    // 获取礼品卡储值金额列表
    rechargeAmount: {},

    // 获取礼品卡详情
    giftCardInfo: {},

    // 获取礼品卡消费记录
    myGiftCardTransactionList: [],
    myGiftCardTransactionParams: {},
    myGiftCardTransactionPagination: {},
    myGiftCardTransactionFinished: false,

    // 获取礼品卡总余额
    myGiftCardAmount: {},

    // 获取礼品卡列表
    giftCardList: [],
    giftCardParams: {},
    giftCardPagination: {},
    giftCardFinished: false,

    // 获取我的礼品卡详情
    myGiftCard: {},

    // 获取我的礼品卡列表
    myGiftCardList: [],
    myGiftCardParams: {},
    myGiftCardPagination: {},
    myGiftCardFinished: false,

    name: '张三',

    // 优惠券中心
    couponList: [],
    couponListFinished: false,
    couponListPagination: {},
    couponListParams: {},
    couponPlatList: [],

    // 我的优惠券
    myCouponList: [],
    myCouponListFinished: false,

    /* 优惠券适用 */

    // 优惠券适用商品列表
    couponProductList: [],
    couponProductListParams: {},
    couponProductListPagination: {},
    couponProductListFinished: false,

    // 优惠券适用商品的优惠券信息
    couponProductCouponInfo: undefined,
    // 优惠券适用商品总价
    couponProductSumPrice: 0,

    couponShopParams: {},
    couponShopList: [],
    couponShopPagination: {},
    couponShopFinished: false,

    invoiceConfig: {},

    selectProductCouponList: [],
  },

  effects: {
    // 活动中的商品列表（新）SPU
    *fetchProductList({ payload }, { select, call, put }) {
      const params = yield select(({ giftCard }) => giftCard.productListParams);
      const curIsFinished = yield select(({ giftCard }) => giftCard.productListFinished);

      const isAlreadyFinished = dealPayloadParams(payload, params, curIsFinished);
      if (isAlreadyFinished) {
        return;
      }

      if (payload.page === 1) {
        yield put({
          type: 'setProductList',
          payload: {
            productList: [],
            productListFinished: false,
          },
        });
      }

      const res = yield call(productListServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }

      const { list: inputList, pagination } = res.content;

      const list = inputList.map((item) => {
        const options = JSON.parse(item.optionValue);
        item.options = options;
        const r = getDefaultOptions(item);

        return {
          ...item,
          options,
          ...r,
        };
      });

      let dataList = [];
      if (payload.page != 1) {
        const oldList = yield select(({ giftCard }) => giftCard.productList);
        dataList = [...oldList, ...list];
      } else {
        dataList = [...list];
      }
      let isFinished = false;
      if (list.length < payload.pageSize) {
        isFinished = true;
      }
      yield put({
        type: 'setProductList',
        payload: {
          productList: dataList,
          productListPagination: { ...pagination },
          productListParams: { ...payload },
          productListFinished: isFinished,
        },
      });
    },

    // 自定义页面获取活动分页列表
    *fetchModuleActivityList({ payload }, { select, call, put }) {
      const params = yield select(({ giftCard }) => giftCard.moduleActivityListParams);
      const curIsFinished = yield select(({ giftCard }) => giftCard.moduleActivityListFinished);

      const isAlreadyFinished = dealPayloadParams(payload, params, curIsFinished);
      if (isAlreadyFinished) {
        return;
      }

      if (payload.page === 1) {
        yield put({
          type: 'setModuleActivityList',
          payload: {
            moduleActivityList: [],
            moduleActivityListFinished: false,
          },
        });
      }

      const res = yield call(moduleActivityListServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }

      const { list, pagination } = res.content;
      let dataList = [];
      if (payload.page != 1) {
        const oldList = yield select(({ giftCard }) => giftCard.moduleActivityList);
        dataList = [...oldList, ...list];
      } else {
        dataList = [...list];
      }
      let isFinished = false;
      if (list.length < payload.pageSize) {
        isFinished = true;
      }
      yield put({
        type: 'setModuleActivityList',
        payload: {
          moduleActivityList: dataList,
          moduleActivityListPagination: { ...pagination },
          moduleActivityListParams: { ...payload },
          moduleActivityListFinished: isFinished,
        },
      });

      return dataList;
    },

    // 获取满减活动的阶梯信息
    *fetchActivityReduces({ payload }, { call, put }) {
      yield put({
        type: 'setActivityReduces',
        payload: undefined,
      });

      const res = yield call(activityReducesServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }

      yield put({
        type: 'setActivityReduces',
        payload: res.content,
      });

      return res.content;
    },

    // 行政编码转行政区
    *getDistrict({ payload }, { call }) {
      const res = yield call(getDistrictServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }
      return res.content;
    },

    // 活动中的商品分页列表
    *fetchActivityProductList({ payload }, { select, call, put }) {
      const params = yield select(({ giftCard }) => giftCard.activityProductListParams);
      const curIsFinished = yield select(({ giftCard }) => giftCard.activityProductListFinished);

      const isAlreadyFinished = dealPayloadParams(payload, params, curIsFinished);
      if (isAlreadyFinished) {
        return;
      }

      if (payload.page === 1) {
        yield put({
          type: 'setActivityProductList',
          payload: {
            activityProductList: [],
          },
        });
      }

      const res = yield call(activityProductListServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }

      const { list, pagination } = res.content;
      let dataList = [];
      if (payload.page != 1) {
        const oldList = yield select(({ giftCard }) => giftCard.activityProductList);
        dataList = [...oldList, ...list];
      } else {
        dataList = [...list];
      }
      let isFinished = false;
      if (dataList.length >= pagination.totalCount) {
        isFinished = true;
      }
      yield put({
        type: 'setActivityProductList',
        payload: {
          activityProductList: dataList,
          activityProductListPagination: { ...pagination },
          activityProductListParams: { ...payload },
          activityProductListFinished: isFinished,
        },
      });
    },
    // 活动适用商品金额结算
    *getActivityProductAmt({ payload }, { call, put }) {
      yield put({
        type: 'setActivityProductAmt',
        payload: {},
      });

      const res = yield call(activityProductAmtServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }

      yield put({
        type: 'setActivityProductAmt',
        payload: res.content,
      });

      return res.content;
    },

    // 活动分页列表
    *fetchActivityList({ payload }, { select, call, put }) {
      const params = yield select(({ giftCard }) => giftCard.activityListParams);
      const curIsFinished = yield select(({ giftCard }) => giftCard.activityListFinished);

      const isAlreadyFinished = dealPayloadParams(payload, params, curIsFinished);
      if (isAlreadyFinished) {
        return;
      }

      const res = yield call(activityListServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }

      const { list, pagination } = res.content;
      let dataList = [];
      if (payload.page != 1) {
        const oldList = yield select(({ giftCard }) => giftCard.activityList);
        dataList = [...oldList, ...list];
      } else {
        dataList = [...list];
      }
      let isFinished = false;
      if (dataList.length >= pagination.totalCount) {
        isFinished = true;
      }
      yield put({
        type: 'setActivityList',
        payload: {
          activityList: dataList,
          activityListPagination: { ...pagination },
          activityListParams: { ...payload },
          activityListFinished: isFinished,
        },
      });
    },

    // 获取礼品卡储值记录
    *fetchOrderList({ payload }, { select, call, put }) {
      const params = yield select(({ giftCard }) => giftCard.orderListParams);
      const curIsFinished = yield select(({ giftCard }) => giftCard.orderListFinished);

      const isAlreadyFinished = dealPayloadParams(payload, params, curIsFinished);
      if (isAlreadyFinished) {
        return;
      }

      const res = yield call(orderListServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }

      const { list, pagination } = res.content;
      let dataList = [];
      if (payload.page != 1) {
        const oldList = yield select(({ giftCard }) => giftCard.orderList);
        dataList = [...oldList, ...list];
      } else {
        dataList = [...list];
      }
      let isFinished = false;
      if (dataList.length >= pagination.totalCount) {
        isFinished = true;
      }
      yield put({
        type: 'setOrderList',
        payload: {
          orderList: dataList,
          orderListPagination: { ...pagination },
          orderListParams: { ...payload },
          orderListFinished: isFinished,
        },
      });
    },

    // 礼品卡储值
    *payGiftCard({ payload }, { call }) {
      const res = yield call(payGiftCardServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }
      return res.content;
    },

    // 获取礼品卡店铺列表
    *fetchGiftCardStoreList({ payload }, { select, call, put }) {
      const params = yield select(({ giftCard }) => giftCard.giftCardStoreParams);
      const curIsFinished = yield select(({ giftCard }) => giftCard.giftCardStoreFinished);

      const isAlreadyFinished = dealPayloadParams(payload, params, curIsFinished);
      if (isAlreadyFinished) {
        return;
      }

      const res = yield call(giftCardStoreListServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }

      const { list, pagination } = res.content;
      let dataList = [];
      if (payload.page != 1) {
        const oldList = yield select(({ giftCard }) => giftCard.giftCardStoreList);
        dataList = [...oldList, ...list];
      } else {
        dataList = [...list];
      }
      let isFinished = false;
      if (dataList.length >= pagination.totalCount) {
        isFinished = true;
      }
      yield put({
        type: 'setGiftCardStoreList',
        payload: {
          giftCardStoreList: dataList,
          giftCardStorePagination: { ...pagination },
          giftCardStoreParams: { ...payload },
          giftCardStoreFinished: isFinished,
        },
      });
    },

    // 获取礼品卡储值金额列表
    *getRechargeAmount({ payload }, { call, put }) {
      yield put({
        type: 'setRechargeAmount',
        payload: {},
      });

      const res = yield call(rechargeAmountServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }

      yield put({
        type: 'setRechargeAmount',
        payload: res.content,
      });

      return res.content;
    },

    // 获取礼品卡详情
    *getGiftCardInfo({ payload }, { call, put }) {
      yield put({
        type: 'setGiftCardInfo',
        payload: {},
      });

      const res = yield call(giftCardInfoServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }

      yield put({
        type: 'setGiftCardInfo',
        payload: res.content,
      });

      return res.content;
    },

    // 礼品卡绑定
    *bindGiftCard({ payload }, { call }) {
      const res = yield call(bindGiftCardServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }
      return res.content;
    },

    // 获取礼品卡消费记录
    *fetchMyGiftCardTransactionList({ payload }, { select, call, put }) {
      const params = yield select(({ giftCard }) => giftCard.myGiftCardTransactionParams);
      const curIsFinished = yield select(({ giftCard }) => giftCard.myGiftCardTransactionFinished);

      const isAlreadyFinished = dealPayloadParams(payload, params, curIsFinished);
      if (isAlreadyFinished) {
        return;
      }

      const res = yield call(myGiftCardTransactionListServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }

      const { list, pagination } = res.content;
      let dataList = [];
      if (payload.page != 1) {
        const oldList = yield select(({ giftCard }) => giftCard.myGiftCardTransactionList);
        dataList = [...oldList, ...list];
      } else {
        dataList = [...list];
      }
      let isFinished = false;
      if (dataList.length >= pagination.totalCount) {
        isFinished = true;
      }
      yield put({
        type: 'setMyGiftCardTransactionList',
        payload: {
          myGiftCardTransactionList: dataList,
          myGiftCardTransactionPagination: { ...pagination },
          myGiftCardTransactionParams: { ...payload },
          myGiftCardTransactionFinished: isFinished,
        },
      });
    },
    // 获取礼品卡总余额
    *getMyGiftCardAmount({ payload }, { call, put }) {
      yield put({
        type: 'setMyGiftCardAmount',
        payload: {},
      });

      const res = yield call(myGiftCardAmountServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }

      yield put({
        type: 'setMyGiftCardAmount',
        payload: res.content,
      });

      return res.content;
    },

    // 获取礼品卡列表
    *fetchGiftCardList({ payload }, { select, call, put }) {
      const params = yield select(({ giftCard }) => giftCard.giftCardParams);
      const curIsFinished = yield select(({ giftCard }) => giftCard.giftCardFinished);

      const isAlreadyFinished = dealPayloadParams(payload, params, curIsFinished);
      if (isAlreadyFinished) {
        return;
      }

      const res = yield call(giftCardListServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }

      const { list, pagination } = res.content;
      let dataList = [];
      if (payload.page != 1) {
        const oldList = yield select(({ giftCard }) => giftCard.giftCardList);
        dataList = [...oldList, ...list];
      } else {
        dataList = [...list];
      }
      let isFinished = false;
      if (dataList.length >= pagination.totalCount) {
        isFinished = true;
      }
      yield put({
        type: 'setGiftCardList',
        payload: {
          giftCardList: dataList,
          giftCardPagination: { ...pagination },
          giftCardParams: { ...payload },
          giftCardFinished: isFinished,
        },
      });
    },
    // 获取我的礼品卡详情
    *getMyGiftCard({ payload }, { call, put }) {
      yield put({
        type: 'setMyGiftCard',
        payload: {},
      });

      const res = yield call(myGiftCardServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }

      yield put({
        type: 'setMyGiftCard',
        payload: res.content,
      });

      return res.content;
    },

    // 获取我的礼品卡列表
    *fetchMyGiftCardList({ payload }, { select, call, put }) {
      const params = yield select(({ giftCard }) => giftCard.myGiftCardParams);
      const curIsFinished = yield select(({ giftCard }) => giftCard.myGiftCardFinished);

      const isAlreadyFinished = dealPayloadParams(payload, params, curIsFinished);
      if (isAlreadyFinished) {
        return;
      }

      const res = yield call(myGiftCardListServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }

      const { list, pagination } = res.content;
      let dataList = [];
      if (payload.page != 1) {
        const oldList = yield select(({ giftCard }) => giftCard.myGiftCardList);
        dataList = [...oldList, ...list];
      } else {
        dataList = [...list];
      }
      let isFinished = false;
      if (dataList.length >= pagination.totalCount) {
        isFinished = true;
      }
      yield put({
        type: 'setMyGiftCardList',
        payload: {
          myGiftCardList: dataList,
          myGiftCardPagination: { ...pagination },
          myGiftCardParams: { ...payload },
          myGiftCardFinished: isFinished,
        },
      });
    },

    *allAddressesModel({ payload }, { call, put }) {
      const res = yield call(allAddressesServer);
      if (res.code === '1') {
        yield put({
          type: 'allAddresses',
          payload: res.content,
        });

        if (payload?.setDefaultAddress !== false) {
          yield put({
            type: 'productCar/setDefaultAddress',
            payload: res.content?.[0] || {},
          });
        }
      }
    },
    *adressDetailModel({ payload }, { call }) {
      const res = yield call(adressDetailServer, payload.id);
      if (res.code === '1') {
        return res.content;
      }
    },
    *adressNewAddModel({ payload }, { call }) {
      const res = yield call(adressNewAddServer, payload);
      if (res.code === '1') {
        return;
      }
    },
    *adressNewEditModel({ payload }, { call }) {
      const res = yield call(adressNewEditServer, payload.parmas, payload.id);
      if (res.code === '1') {
        return;
      }
    },
    *adressDeleteModel({ payload }, { call }) {
      const res = yield call(adressDeleteServer, payload);
      if (res.code === '1') {
        Taro.showToast({
          title: '删除地址成功',
          duration: 2000,
          icon: 'none',
        });
        sleep(2000).then(() => {
          Taro.navigateBack();
        });
        return;
      } else {
        Taro.showToast({
          title: '删除地址失败',
          duration: 1500,
          icon: 'none',
        });
      }
    },

    *getAppConfiguration({ payload }, { call, put }) {
      const res = yield call(getAppConfigurationServer, payload);
      if (res.code === '1') {
        yield put({
          type: 'setAppConfiguration',
          payload: {
            appConfiguration: { ...res.content },
          },
        });
      } else {
        Taro.showToast({
          title: '获取平台配置失败',
          duration: 1000,
          icon: 'none',
        });
      }
    },

    *getHotCouponList({ payload }, { call, put }) {
      const res = yield call(hotCouponListServer, payload);
      if (res.code === '1') {
        yield put({
          type: 'setHotCouponList',
          payload: {
            couponPlatList: [...res.content],
          },
        });
      } else {
        Taro.showToast({
          title: '获取平台券失败',
          duration: 1000,
          icon: 'none',
        });
      }
    },

    *getDirectionalCouponList({ payload }, { call, put }) {
      const res = yield call(directionalCouponListServer, payload);
      if (res.code === '1') {
        yield put({
          type: 'setDirectionalCouponList',
          payload: {
            directionalCouponList: { ...res.content },
          },
        });
      } else {
        Taro.showToast({
          title: '获取专属优惠券失败',
          duration: 1500,
          icon: 'none',
        });
      }
    },

    *receiveDirectionalCoupon({ payload }, { call }) {
      const res = yield call(receiveDirectionalCouponServer, payload);
      if (res.code === '1') {
        Taro.showToast({
          title: '领取成功',
          duration: 2000,
          icon: 'none',
        });
      } else {
        Taro.showToast({
          title: '领取专属优惠券失败',
          duration: 1500,
          icon: 'none',
        });
      }
    },

    *getCouponList({ payload }, { select, call, put }) {
      const params = yield select(({ giftCard }) => giftCard.couponListParams);
      const curIsFinished = yield select(({ giftCard }) => giftCard.couponListFinished);

      const isAlreadyFinished = dealPayloadParams(payload, params, curIsFinished);
      if (isAlreadyFinished) {
        return;
      }

      const res = yield call(couponListServer, payload);
      if (res.code == 1) {
        const { list, pagination } = res.content;
        let dataList = [];
        if (payload.page != 1) {
          const curDataList = yield select(({ giftCard }) => giftCard.couponList);
          dataList = [...curDataList, ...list];
        } else {
          dataList = [...list];
        }
        let isFinished = false;
        if (dataList.length >= pagination.totalCount) {
          isFinished = true;
        }
        yield put({
          type: 'setCouponList',
          payload: {
            couponList: dataList,
            couponListPagination: { ...pagination },
            couponListParams: { ...payload },
            couponListFinished: isFinished,
          },
        });
      } else {
        Taro.showToast({
          title: '获取券失败',
          duration: 1000,
          icon: 'none',
        });
      }
    },

    *createCoupon({ payload }, { call }) {
      const { code, content } = yield call(createCouponServer, payload);

      if (code === '1') {
        return content;
      } else {
        return Promise.reject();
      }
    },

    *myCoupon({ payload: { page }, payload }, { put, call, select }) {
      let finished = yield select(({ giftCard: { myCouponListFinished } }) => {
        return myCouponListFinished;
      });

      // 已到最后一页
      if (finished) {
        return;
      }

      const { code, content } = yield call(myCouponServer, payload);

      if (code !== '1') {
        return;
      }

      const { list = [], pagination } = content ?? {};

      // 没有下一页了
      if (pagination && page >= pagination.totalPage) {
        yield put({ type: 'setMyCouponListFinished', payload: true });
      }

      if (page === 1) {
        yield put({
          type: 'setMyCouponList',
          payload: list,
        });
      } else {
        let myCouponList = yield select((state) => state.giftCard.myCouponList);

        yield put({
          type: 'setMyCouponList',
          payload: [...myCouponList, ...list],
        });
      }
    },

    *getOrderCouponList({ payload }, { put, call }) {
      const { code, content } = yield call(orderCouponListServer, payload);

      if (code !== '1') {
        return;
      }

      const { usableCouponList = [] } = content ?? {};
      usableCouponList.length > 0 &&
        usableCouponList.map((item) => {
          item.selected = 2;
        });

      yield put({
        type: 'setOrderCouponList',
        payload: {
          sourceType: payload.sourceType,
          ...content,
          usableCouponList,
        },
      });
    },

    // 优惠券适用商品列表
    *fetchCouponProductList({ payload }, { select, call, put }) {
      const params = yield select(({ giftCard }) => giftCard.couponProductListParams);
      const curIsFinished = yield select(({ giftCard }) => giftCard.couponProductListFinished);

      const isAlreadyFinished = dealPayloadParams(payload, params, curIsFinished);
      if (isAlreadyFinished) {
        return;
      }

      if (payload.page === 1) {
        yield put({
          type: 'setCouponProductList',
          payload: {
            couponProductList: [],
            couponProductListFinished: false,
          },
        });
      }

      const res = yield call(couponProductsInfoServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }

      const { list, pagination } = res.content;
      let dataList = [];
      if (payload.page != 1) {
        const oldList = yield select(({ giftCard }) => giftCard.couponProductList);
        dataList = [...oldList, ...list];
      } else {
        dataList = [...list];
      }
      let isFinished = false;
      if (list.length < payload.pageSize) {
        isFinished = true;
      }
      yield put({
        type: 'setCouponProductList',
        payload: {
          couponProductList: dataList,
          couponProductListPagination: { ...pagination },
          couponProductListParams: { ...payload },
          couponProductListFinished: isFinished,
        },
      });
    },

    *getCouponProductInCartPrice({ payload }, { call, put }) {
      const { code, content: { productAmount } = {} } = yield call(
        getCouponProductInCartPriceServer,
        payload,
      );

      if (code === '1') {
        yield put({
          type: 'setCouponProductSumPrice',
          payload: productAmount ?? 0,
        });
      }
    },

    *getCouponShopListModel({ payload }, { select, call, put }) {
      const params = yield select(({ giftCard }) => giftCard.couponShopParams);
      const curIsFinished = yield select(({ giftCard }) => giftCard.couponShopFinished);

      const isAlreadyFinished = dealPayloadParams(payload, params, curIsFinished);
      if (isAlreadyFinished) {
        return;
      }

      const res = yield call(couponShopListServer, payload);
      if (res.code == 1) {
        const { list, pagination } = res.content;
        let dataList = [];
        if (payload.page != 1) {
          const curDataList = yield select(({ giftCard }) => giftCard.couponShopList);
          dataList = [...curDataList, ...list];
        } else {
          dataList = [...list];
        }
        let isFinished = false;
        if (dataList.length >= pagination.totalCount) {
          isFinished = true;
        }
        yield put({
          type: 'setCouponShopList',
          payload: {
            couponShopList: dataList,
            couponShopPagination: { ...pagination },
            couponShopParams: { ...payload },
            couponShopFinished: isFinished,
          },
        });
      } else {
        Taro.showToast({
          title: '获取券适用商户失败',
          duration: 1000,
          icon: 'none',
        });
      }
    },

    *getInvoiceConfig({ payload }, { call, put }) {
      const res = yield call(getInvoiceConfigServer, payload);
      if (res.code === '1') {
        let { display, infoList = [] } = res.content;
        let commonEnable = false; //纸质普通发票
        if (display === 1) {
          for (let i = 0; i < infoList.length; i++) {
            if (infoList[i].einvoiceType === 1 && infoList[i].status === 1) {
              commonEnable = true;
            }
          }
        }
        res.content.commonEnable = commonEnable;
        yield put({
          type: 'setInvoiceConfig',
          payload: {
            invoiceConfig: { ...res.content },
          },
        });
      } else {
        Taro.showToast({
          title: '获取商家开票配置失败',
          duration: 1000,
          icon: 'none',
        });
      }
    },

    *selectProductCouponList({ payload }, { call, put }) {
      const res = yield call(selectProductCouponListServer, payload);
      if (res.code === '1') {
        yield put({
          type: 'setSelectProductCouponList',
          payload: {
            selectProductCouponList: [...res.content],
          },
        });
      } else {
        Taro.showToast({
          title: '获取商品可用券失败',
          duration: 1000,
          icon: 'none',
        });
      }
    },
  },
  reducers: {
    // 活动中的商品列表（新）SPU
    setProductList(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    // 自定义页面获取活动分页列表
    setModuleActivityList(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    // 获取满减活动的阶梯信息
    setActivityReduces(state, { payload }) {
      return {
        ...state,
        activityReduces: payload,
      };
    },

    // 未登录时, 领取优惠券数据存储, 用于登录后直接领取优惠券
    setPendingCoupon(state, { payload }) {
      return {
        ...state,
        pendingCoupon: payload,
      };
    },
    // 活动中的商品分页列表
    setActivityProductList(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    // 活动适用商品金额结算
    setActivityProductAmt(state, { payload }) {
      return {
        ...state,
        activityProductAmt: payload,
      };
    },

    // 活动分页列表
    setActivityList(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    // 获取礼品卡储值记录
    setOrderList(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    // 获取礼品卡店铺列表
    setGiftCardStoreList(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    // 获取礼品卡储值金额列表
    setRechargeAmount(state, { payload }) {
      return {
        ...state,
        rechargeAmount: payload,
      };
    },

    // 获取礼品卡详情
    setGiftCardInfo(state, { payload }) {
      return {
        ...state,
        giftCardInfo: payload,
      };
    },

    // 获取礼品卡消费记录
    setMyGiftCardTransactionList(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    // 获取礼品卡总余额
    setMyGiftCardAmount(state, { payload }) {
      return {
        ...state,
        myGiftCardAmount: payload,
      };
    },

    // 获取礼品卡列表
    setGiftCardList(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    // 获取我的礼品卡详情
    setMyGiftCard(state, { payload }) {
      return {
        ...state,
        myGiftCard: payload,
      };
    },

    // 获取我的礼品卡列表
    setMyGiftCardList(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    adressId(state, { payload }) {
      return { ...state, adressId: payload };
    },
    allAddresses(state, { payload }) {
      return { ...state, allAddresses: payload };
    },

    resetCouponList(state, {}) {
      return {
        ...state,
        couponList: [],
        couponListPagination: undefined,
        couponListFinished: false,
      };
    },
    setCouponListPagination(state, { payload }) {
      return {
        ...state,
        couponListPagination: payload,
      };
    },
    setCouponListPure(state, { payload }) {
      return {
        ...state,
        couponList: [...payload],
      };
    },
    setCouponList(state, { payload }) {
      const { couponList, couponListPagination, couponListParams, couponListFinished } = payload;
      return {
        ...state,
        couponList,
        couponListPagination,
        couponListParams,
        couponListFinished,
      };
    },
    setCouponListFinished(state, { payload }) {
      return { ...state, couponListFinished: payload };
    },
    setAppConfiguration(state, { payload }) {
      let { appConfiguration } = payload;
      return {
        ...state,
        appConfiguration,
      };
    },
    setHotCouponList(state, { payload }) {
      let { couponPlatList } = payload;
      return {
        ...state,
        couponPlatList,
      };
    },

    setDirectionalCouponList(state, { payload }) {
      let { directionalCouponList } = payload;
      return {
        ...state,
        directionalCouponList,
      };
    },

    resetDirectionalCoupon(state, {}) {
      return {
        ...state,
        directionalCouponList: undefined,
      };
    },

    resetMyCouponList(state, {}) {
      return {
        ...state,
        myCouponList: [],
        myCouponListFinished: false,
      };
    },
    setMyCouponList(state, { payload }) {
      return { ...state, myCouponList: payload };
    },
    setMyCouponListFinished(state, { payload }) {
      return { ...state, myCouponListFinished: payload };
    },

    resetOrderCouponListPlat(state) {
      return {
        ...state,
        usableCouponListPlat: undefined,
        disabledCouponListPlat: undefined,
        selectedCouponListPlat: undefined,
        discountAmountPlat: undefined,
      };
    },
    resetOrderCouponListAll(state) {
      return {
        ...state,

        usableCouponListPlat: undefined,
        disabledCouponListPlat: undefined,
        selectedCouponListPlat: undefined,
        discountAmountPlat: undefined,

        usableCouponList: undefined,
        disabledCouponList: undefined,
        selectedCouponList: undefined,
        discountAmount: undefined,

        isAutoCouponDone: undefined,
      };
    },
    setOrderCouponListAll(state, { payload }) {
      const { usableCouponList = [], usableCouponListPlat = [] } = payload;
      const { selectedCouponList, discountAmount } = getUsableSelectedCouponList(usableCouponList);
      const {
        selectedCouponList: selectedCouponListPlat,
        discountAmount: discountAmountPlat,
      } = getUsableSelectedCouponList(usableCouponListPlat);
      return {
        ...state,
        usableCouponList,
        selectedCouponList,
        discountAmount,
        usableCouponListPlat,
        selectedCouponListPlat,
        discountAmountPlat,
        isAutoCouponDone: true,
      };
    },
    setOrderCouponList(state, { payload }) {
      const { usableCouponList = [], disabledCouponList = [], sourceType } = payload;

      const { selectedCouponList, discountAmount } = getUsableSelectedCouponList(usableCouponList);

      if (sourceType == 1) {
        //商家券
        if (
          state.usableCouponListPlat &&
          state.selectedCouponListPlat?.length > 0 &&
          selectedCouponList?.length > 0 &&
          state.selectedCouponListPlat[0].activityType?.indexOf('2') == -1
        ) {
          //已选平台券，且该平台券不可与商家券叠加使用，则清除已选平台券
          let usableCouponListPlatOrg = resetSelectedStatus(state.usableCouponListPlat);
          return {
            ...state,
            usableCouponList,
            disabledCouponList,
            selectedCouponList,
            discountAmount,
            usableCouponListPlat: usableCouponListPlatOrg,
            selectedCouponListPlat: undefined,
            discountAmountPlat: undefined,
          };
        }

        return {
          ...state,
          usableCouponList,
          disabledCouponList,
          selectedCouponList,
          discountAmount,
        };
      } else {
        //平台券
        if (
          state.usableCouponList &&
          state.selectedCouponList?.length > 0 &&
          selectedCouponList?.length > 0 &&
          selectedCouponList[0].activityType?.indexOf('2') == -1
        ) {
          //已选商家券，且该平台券不可与商家券叠加使用，则清除已选商家券
          let usableCouponListOrg = resetSelectedStatus(state.usableCouponList);
          return {
            ...state,
            usableCouponList: usableCouponListOrg,
            selectedCouponList: undefined,
            discountAmount: undefined,
            usableCouponListPlat: usableCouponList,
            disabledCouponListPlat: disabledCouponList,
            selectedCouponListPlat: selectedCouponList,
            discountAmountPlat: discountAmount,
          };
        }
        return {
          ...state,
          usableCouponListPlat: usableCouponList,
          disabledCouponListPlat: disabledCouponList,
          selectedCouponListPlat: selectedCouponList,
          discountAmountPlat: discountAmount,
        };
      }
    },

    /* 优惠券适用商品 */
    resetCouponProductsInfo(state, {}) {
      return {
        ...state,
        couponProductSumPrice: 0,
        couponProductList: undefined,
        couponProductInfo: undefined,
        couponProductListFinished: false,
      };
    },
    setCouponProductCouponInfo(state, { payload }) {
      return {
        ...state,
        couponProductCouponInfo: payload,
      };
    },
    // 优惠券适用商品列表
    setCouponProductList(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    // 添加商品, 计算当前优惠券商品总价
    addProductToCouponProductSumPrice(state, { payload }) {
      return {
        ...state,
        couponProductSumPrice: state.couponProductSumPrice + Number(payload),
      };
    },
    // 设置在购物车中当前优惠券商品总价
    setCouponProductSumPrice(state, { payload }) {
      return {
        ...state,
        couponProductSumPrice: (state.couponProductSumPrice ?? 0) + Number(payload),
      };
    },

    setCouponShopList(state, { payload }) {
      const {
        couponShopList,
        couponShopPagination,
        couponShopParams,
        couponShopFinished,
      } = payload;
      return {
        ...state,
        couponShopList,
        couponShopPagination,
        couponShopParams,
        couponShopFinished,
      };
    },

    setInvoiceConfig(state, { payload }) {
      const { invoiceConfig } = payload;
      return {
        ...state,
        invoiceConfig,
      };
    },

    setSelectProductCouponList(state, { payload }) {
      const { selectProductCouponList } = payload;
      return {
        ...state,
        selectProductCouponList,
      };
    },
  },
};
